<template>
  <el-dialog
    v-model="visible"
    :title="formData.id ? '编辑入库单' : '新增入库单'"
    width="800px"
    @close="handleClose"
    class="inbound-form-dialog"
  >
    <el-form 
      :model="formData" 
      :rules="rules" 
      ref="formRef" 
      label-width="120px"
      class="inbound-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入库单号" prop="inboundNumber">
            <el-input 
              v-model="formData.inboundNumber" 
              :disabled="!!formData.id"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商" prop="supplierId">
            <el-select 
              v-model="formData.supplierId" 
              placeholder="请选择供应商" 
              class="form-item-width form-select"
              @change="handleSupplierChange"
            >
              <el-option
                v-for="supplier in suppliers"
                :key="supplier.id"
                :label="supplier.name"
                :value="supplier.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="入库日期" prop="inboundDate">
            <el-date-picker
              v-model="formData.inboundDate"
              type="date"
              placeholder="选择日期"
              style="width: 100%"
              value-format="YYYY-MM-DD"
              class="form-date-picker"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="运费" prop="freight">
            <el-input-number 
              v-model="formData.freight" 
              :min="0" 
              :precision="2" 
              :step="100"
              style="width: 100%"
              class="form-input-number"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="是否含票" prop="hasInvoice">
        <el-switch 
          v-model="formData.hasInvoice" 
          class="form-switch"
        />
      </el-form-item>
      
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="formData.remark" 
          type="textarea" 
          :rows="2"
          class="form-textarea"
        />
      </el-form-item>
      
      <!-- 商品明细 -->
      <el-divider>商品明细</el-divider>
      <el-table :data="formData.items" style="width: 100%" class="items-table">
        <el-table-column label="商品名称" width="200">
          <template #default="scope">
            <el-select
              v-model="scope.row.productId"
              filterable
              remote
              :remote-method="searchProducts"
              :loading="productLoading"
              placeholder="请选择商品"
              style="width: 100%"
              @change="(val: number | string) => handleProductChange(val, scope.row)"
              class="table-select"
            >
              <el-option
                v-for="product in products"
                :key="product.id"
                :label="product.name"
                :value="product.id"
              >
                <span style="float: left">{{ product.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  {{ product.specification }}
                </span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="规格" width="150">
          <template #default="scope">
            <el-input 
              v-model="scope.row.specification" 
              placeholder="规格" 
              :disabled="!!scope.row.productId"
              class="table-input"
            />
          </template>
        </el-table-column>
        <el-table-column label="数量" width="100">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.quantity" 
              :min="1" 
              @change="(val: number | undefined) => handleQuantityChange(val, scope.row)"
              class="table-input-number"
            />
          </template>
        </el-table-column>
        <el-table-column label="单价" width="100">
          <template #default="scope">
            <el-input-number 
              v-model="scope.row.unitPrice" 
              :min="0" 
              :precision="2"
              @change="(val: number | undefined) => handleUnitPriceChange(val, scope.row)"
              class="table-input-number"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额" width="100">
          <template #default="scope">
            {{ (scope.row.quantity * scope.row.unitPrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button 
              @click="removeItem(scope.$index)" 
              type="danger" 
              size="small"
              class="table-action-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px;">
        <el-button 
          @click="addItem" 
          type="primary" 
          :icon="Plus"
          class="add-item-btn"
        >
          添加商品
        </el-button>
      </div>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-form-item label="总金额">
            <el-input v-model="totalAmount" readonly class="form-input" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发票状态" prop="invoiceStatus">
            <el-select 
              v-model="formData.invoiceStatus" 
              placeholder="请选择发票状态" 
              :disabled="!formData.hasInvoice"
              class="form-item-width form-select"
            >
              <el-option label="待开票" value="pending" />
              <el-option label="已收票（未上传）" value="received" />
              <el-option label="已上传" value="uploaded" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitLoading"
          class="submit-btn"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'

interface Supplier {
  id: number
  name: string
}

interface Product {
  id: number
  name: string
  specification: string
  unitPrice: number
}

interface InboundOrderItem {
  id: number
  productId: number | null
  productName: string
  specification: string
  quantity: number
  unitPrice: number
}

interface InboundOrder {
  id: number
  inboundNumber: string
  supplierId: number
  inboundDate: string
  totalAmount: number
  hasInvoice: boolean
  invoiceStatus: string
  freight: number
  remark: string
  items: InboundOrderItem[]
}

const props = defineProps<{
  modelValue: boolean
  formData: InboundOrder
  suppliers: Supplier[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', data: InboundOrder): void
  (e: 'close'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const productLoading = ref(false)
const products = ref<Product[]>([])

// 计算属性
const totalAmount = computed(() => {
  const itemsTotal = props.formData.items.reduce((sum, item) => {
    return sum + (item.quantity * item.unitPrice)
  }, 0)
  return (itemsTotal + props.formData.freight).toFixed(2)
})

// 表单验证规则
const rules = ref<FormRules>({
  inboundNumber: [
    { required: true, message: '请输入入库单号', trigger: 'blur' }
  ],
  supplierId: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  inboundDate: [
    { required: true, message: '请选择入库日期', trigger: 'change' }
  ]
})

// 方法
const handleClose = () => {
  emit('close')
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 更新总金额
        const data = { ...props.formData }
        data.totalAmount = parseFloat(totalAmount.value)
        emit('submit', data)
        handleClose()
        ElMessage.success('保存成功')
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const addItem = () => {
  props.formData.items.push({
    id: Date.now(),
    productId: null,
    productName: '',
    specification: '',
    quantity: 1,
    unitPrice: 0
  })
  ElMessage.info('已添加新商品行')
}

const removeItem = (index: number) => {
  ElMessageBox.confirm(
    '确定要删除这个商品吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    props.formData.items.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleSupplierChange = (supplierId: number) => {
  const supplier = props.suppliers.find(s => s.id === supplierId)
  // 可以根据供应商设置默认值
  if (supplier) {
    ElMessage.info(`已选择供应商: ${supplier.name}`)
  }
}

const searchProducts = (query: string) => {
  if (!query) {
    products.value = []
    return
  }
  
  productLoading.value = true
  // 模拟搜索商品
  setTimeout(() => {
    products.value = [
      { id: 1, name: '服务器', specification: '高性能计算服务器', unitPrice: 25000 },
      { id: 2, name: '显示器', specification: '27寸4K显示器', unitPrice: 3500 },
      { id: 3, name: '键盘', specification: '机械键盘', unitPrice: 500 }
    ].filter(product => product.name.includes(query))
    productLoading.value = false
  }, 300)
}

const handleProductChange = (productId: number | string, row: InboundOrderItem) => {
  if (typeof productId === 'number') {
    const product = products.value.find(p => p.id === productId)
    if (product) {
      row.productName = product.name
      row.specification = product.specification
      row.unitPrice = product.unitPrice
      ElMessage.success(`已选择商品: ${product.name}`)
    }
  }
}

const handleQuantityChange = (value: number | undefined, row: InboundOrderItem) => {
  // 数量变化时可以添加业务逻辑
  if (value !== undefined) {
    console.log('数量变化:', value)
  }
}

const handleUnitPriceChange = (value: number | undefined, row: InboundOrderItem) => {
  // 单价变化时可以添加业务逻辑
  if (value !== undefined) {
    console.log('单价变化:', value)
  }
}

// 监听含票状态变化
watch(() => props.formData.hasInvoice, (newValue) => {
  if (!newValue) {
    props.formData.invoiceStatus = ''
  } else if (!props.formData.invoiceStatus) {
    props.formData.invoiceStatus = 'pending'
  }
})
</script>

<style scoped>
.inbound-form-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.inbound-form {
  max-height: 70vh;
  overflow-y: auto;
}

.items-table {
  margin-bottom: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单元素悬停效果 */
.form-input:hover,
.form-select:hover,
.form-input-number:hover,
.form-date-picker:hover,
.form-textarea:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 开关组件特殊样式 */
.form-switch {
  transition: all 0.3s ease;
}

.form-switch:hover {
  transform: scale(1.1);
}

/* 表格输入框悬停效果 */
.table-input:hover,
.table-input-number:hover,
.table-select:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 表格操作按钮悬停效果 */
.table-action-btn,
.add-item-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.table-action-btn:hover,
.add-item-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 取消按钮悬停效果 */
.cancel-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.cancel-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 提交按钮悬停效果 */
.submit-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .inbound-form-dialog {
    width: 95% !important;
    margin-top: 20px;
  }
  
  .el-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .el-col {
    width: 100%;
  }
  
  .items-table :deep(.el-table__body-wrapper) {
    overflow-x: auto;
  }
}
</style>